package main

import (
	"fmt"
	"github.com/spf13/cobra"
)

func LoadSm2PublicKey(pubKeyFileName string) error {

	pubKey, err := Read_sm2_public_pem_file(pubKeyFileName)
	if err != nil {
		return err
	}
	fmt.Printf("SM2 public key: (%x, %x)\n", pubKey.X, pubKey.Y)
	return nil
}

func LoadRsaPublicKey(pubKeyFileName string) error {

	pubKey, err := Read_rsa_public_pem_file(pubKeyFileName)
	if err != nil {
		return err
	}
	fmt.Printf("Rsa public key: N=%x, E=%x\n", pubKey.N, pubKey.E)
	return nil
}

var loadPubCmd = &cobra.Command{
	Use:   "loadPub",
	Short: "从文件中加载公钥测试命令",
	Long: `例如：gmTool.exe loadPub --public [公钥PEM文件名]
	`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("generate key called")

		pubFileName, err := cmd.Flags().GetString("public")
		if err != nil {
			fmt.Printf("Error: %v\n", err.Error())
			return
		}
		if !FileExist(pubFileName) {
			fmt.Printf("Error: 公钥文件 %v 不存在！\n", pubFileName)
			return
		}

		keyType, err := cmd.Flags().GetString("keyType")

		if keyType == "sm2" {
			err = LoadSm2PublicKey(pubFileName)
			if err != nil {
				fmt.Printf("Error: %v\n", err.Error())
				return
			}
		} else if keyType == "rsa" {
			err = LoadRsaPublicKey(pubFileName)
			if err != nil {
				fmt.Printf("Error: %v\n", err.Error())
				return
			}
		} else {
			fmt.Printf("未知的密钥类型: %s\n", keyType)
		}

	},
}

func init() {
	rootCmd.AddCommand(loadPubCmd)

	// Here you will define your flags and configuration settings.
	loadPubCmd.Flags().StringP("public", "g", "public.pem", "公钥PEM文件名称")
	loadPubCmd.Flags().StringP("keyType", "t", "sm2", "私钥类型，sm2或rsa，默认为sm2")
}
